package com.example.student_blocket;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class AdsDetailActivity extends Activity implements OnClickListener {
	
	private final String LOAD_AN_AD = Singleton.getInstance().getHOST() + "shop-app/select-one-ad.php";
	private final String OWNER_DETAILS = Singleton.getInstance().getHOST() + "shop-app/get-owner-details.php";
	private Intent intent;
	
	private TextView titleView;
	private TextView priceView;
	private ImageView imageView;
	private TextView descriptionView;
	private TextView ownerDetailsView;
	
	private Button callTheSeller;
	private Button emailTheSeller;
	
	private Misc misc = new Misc();
	//TODO are we going to put them in the detail ad view?
	@SuppressWarnings("unused")
	private String currentCategory;
	@SuppressWarnings("unused")
	private String currentDate;
	
	private String currentID;
	private String currentTitle;
	private String currentPrice;
	private String currentDescription;
	private String currentImageURI;
	private Bitmap currentImage;
	private String currentOwner;
	private String ownerNames;
	private String ownerPhone;
	private String ownerEmail;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		setContentView(R.layout.activity_ads_detail);
		iniGUIComponents();
		
		intent = getIntent();
		currentID = intent.getExtras().getString("id");
		new LoadAnAd().execute();
	}

	@Override
	public void onClick(View v) {
		if (v == callTheSeller) {
			try {
            	Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:"+ ownerPhone));
                startActivity(callIntent);
            } catch (ActivityNotFoundException activityException) {}
		} else if(v == emailTheSeller) {
			Intent sendIntent = new Intent(Intent.ACTION_VIEW);
			sendIntent.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");
			sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { ownerEmail});
			sendIntent.setData(Uri.parse("demo@gmail.com"));
			sendIntent.putExtra(Intent.EXTRA_SUBJECT, currentTitle);
			sendIntent.setType("plain/text");
			sendIntent.putExtra(Intent.EXTRA_TEXT, "Insert text here.");
			startActivity(sendIntent);
		}
	}
	@Override
	public void onBackPressed() {
		startActivity(new Intent(AdsDetailActivity.this, AdsActivity.class));
		finish();
	}
	private void iniGUIComponents() {
		titleView = (TextView) findViewById(R.id.ADetails_title);
		priceView = (TextView) findViewById(R.id.ADetail_Price);
		imageView = (ImageView) findViewById(R.id.ADetail_Image);
		descriptionView = (TextView) findViewById(R.id.ADetail_Description);
		ownerDetailsView = (TextView) findViewById(R.id.ADetails_owner);
		
		callTheSeller = (Button) findViewById(R.id.call_seller);
		callTheSeller.setOnClickListener(this);
		emailTheSeller = (Button) findViewById(R.id.email_seller);
		emailTheSeller.setOnClickListener(this);
	}

	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.ads_detail, menu);
		return true;
	}
	
	private class LoadAnAd extends AsyncTask<String, String, String> {
		private ProgressDialog pDialog;
		@Override
		protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(AdsDetailActivity.this);
	        pDialog.setMessage("Loading The Ad...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(true);
	        pDialog.show();
	    }
		@Override
		protected String doInBackground(String... params) {
			JSONParser jParser = new JSONParser();
			List<NameValuePair> values = new ArrayList<NameValuePair>();
			values.add(new BasicNameValuePair("id", currentID));
            JSONObject json = jParser.makeHttpRequest(LOAD_AN_AD, values);
            try {
                int success = json.getInt("affected");
 
                if (success == 1) {
                    currentTitle = json.getString("title");
                    currentPrice = json.getString("price");
                    currentImageURI = json.getString("image");
                    currentDate = json.getString("date");
                    currentCategory = json.getString("category");
                    currentDescription = json.getString("description");
                    currentOwner = json.getString("owner");  
                    currentImage = misc.getImage(currentImageURI);
					
                    
                    List<NameValuePair> values1 = new ArrayList<NameValuePair>();
        			values1.add(new BasicNameValuePair("username", currentOwner));
                    JSONObject json1 = jParser.makeHttpRequest(OWNER_DETAILS, values1);
                    int success1 = json1.getInt("affected");
                    if (success1 == 1) {
                        ownerNames = json1.getString("first_name")+" "+json1.getString("last_name");
                        ownerPhone = json1.getString("telephone");
                        ownerEmail = json1.getString("email");
					} else {
	                    Intent i = new Intent(getApplicationContext(), AdsActivity.class);
	                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	                    startActivity(i);
	                }
                    
                } else {
                    Intent i = new Intent(getApplicationContext(), AdsActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
 
            return null;
        }
 
		@Override
		protected void onPostExecute(String op) {
			pDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
				public void run() {
                	setTheView();
                }
            });
        }
	}
	
	private void setTheView() {
		titleView.setText(currentTitle);
		priceView.setText(currentPrice);
		descriptionView.setText(currentDescription);
		ownerDetailsView.setText("Seller's names: "+ ownerNames +
				"\n"+"Email: "+ownerEmail +
				"\n"+"Phone Num: "+ownerPhone);
		imageView.setImageBitmap(currentImage);
	}
}
